# 实现多帐号登录
import re
from django.contrib.auth.backends import ModelBackend
from apps.registers.models import User

def Muchsend(username):
    if re.match(r"^1[3-9]{1}\d{9}$",username):
        # 匹配成功后判断表单传入的mobile和数据库中的是否一样
        user = User.objects.get(mobile=username)
    else:
        re.match(r"^[0-9a-zA-Z]{5,20}$",username)
        user = User.objects.get(username=username)
    return user


class Remodelbackend(ModelBackend):
    """
    当前的系统登录不能满足我的需要,所以需要重写系统的authenticate方法
    """
    def authenticate(self, request, username=None, password=None, **kwargs):
        """判断是登录帐号使用户名还是手机号,这里正则匹配用户名即可,因为用户用手机号登录
        也是通过用户名这个表单"""
        # if re.match(r"^1[3-9]{1}\d{9}$",username):
        #     # 匹配成功后判断表单传入的mobile和数据库中的是否一样
        #     user = User.objects.get(mobile=username)
        # else:
        #     re.match(r"^[0-9a-zA-Z]{5,20}$",username)
        #     user = User.objects.get(username=username)
        user = Muchsend(username)
        if user and user.check_password(raw_password=password):
            return user
